﻿/** 
* 字符串为javascript转码。
*/
String.prototype.encode4Js = function() {
    var o = [/\\/g, /"/g, /'/g, /\//g, /\r/g, /\n/g];
    var n = ["\\u005C", "\\u0022", "\\u0027", "\\u002F", "\\u000A", "\\u000D"];
    var s = this;
    for (var i = 0; i < o.length; i++) {
        s = s.replace(o[i], n[i]);
    }
    return s;
};

/**
* 序列化一个对象(只序列化String,Number,Date,Array,Json对象和有serialize2Str方法的对象,其它的对象都会被序列化成null)
* @memberof Object
* @param obj { Object } 需要序列化的Json、Array对象或其它对象
* @return 序列化后的字符串
* @type String
*/
Object.serialize2Str = function(obj) {
    if (obj == null) return null;
    if (obj.serialize2Str) return obj.serialize2Str();
    var cst = obj.constructor;
    switch (cst) {
        case String: return '"' + obj.encode4Js() + '"';
        case Number: return obj + "";
        case Date: return 'new Date(' + obj.getTime() + ')';
        case Array:
            var ar = [];
            for (var i = 0; i < obj.length; i++) ar[i] = Object.serialize2Str(obj[i]);
            return '[' + ar.join(',') + ']';
        case Object:
            var ar = [];
            for (var i in obj) {
                ar.push('"' + (i + '').encode4Js() + '":' + Object.serialize2Str(obj[i]));
            }
            return '{' + ar.join(',') + '}';
    }
    return null;
};